import time
import traceback

import streamlit as st
import pandas as pd
import json
import os
import datetime
import uuid
import io
from dotenv import load_dotenv
from tools import (request_dify, judge_by_ai, read_data_file, 
                  split_tags, join_tags, generate_analysis_report,
                  create_score_pie_chart, create_tag_bar_chart,
                  show_analysis_report, logger)

from config import (DEEPSEEK_MODELS, OPENAI_MODELS, output_folder,
                    FIELD_QUESTION, FIELD_EXPECTED_ANSWER, FIELD_ACTUAL_ANSWER,
                    FIELD_ACCURACY, FIELD_RELEVANCE, FIELD_COHERENCE, FIELD_TOXICITY, FIELD_TAGS, FIELD_FINAL_SCORE,
                    FIELD_COMMENT, sample_file, JUDGEMENT_PROMPT)

# 加载环境变量
load_dotenv()
# logger.info("应用程序启动")

# 设置页面配置
st.set_page_config(
    page_title="AI 测试工具",
    page_icon="🤖",
    layout="wide",
    initial_sidebar_state="expanded"
)

# 初始化会话状态
if 'projects' not in st.session_state:
    st.session_state.projects = []
if 'current_project' not in st.session_state:
    st.session_state.current_project = None
if 'test_results' not in st.session_state:
    st.session_state.test_results = {}
if 'show_evaluation_modal' not in st.session_state:
    st.session_state.show_evaluation_modal = False
if 'current_question' not in st.session_state:
    st.session_state.current_question = None
if 'current_answer' not in st.session_state:
    st.session_state.current_answer = None
if 'chat_history' not in st.session_state:
    st.session_state.chat_history = []
if 'current_chat_id' not in st.session_state:
    st.session_state.current_chat_id = None
if 'manual_url' not in st.session_state:
    st.session_state.manual_url = ""
if 'manual_api_key' not in st.session_state:
    st.session_state.manual_api_key = ""
if 'manual_user' not in st.session_state:
    st.session_state.manual_user = ""
if 'new_project_interface' not in st.session_state:
    st.session_state.new_project_interface = "Dify"  # 设置默认值为Dify
if 'show_analysis_report' not in st.session_state:
    st.session_state.show_analysis_report = False
if 'selected_tags' not in st.session_state:
    st.session_state.selected_tags = []
if 'show_custom_prompt_dialog' not in st.session_state:
    st.session_state.show_custom_prompt_dialog = False


# 创建新项目
def create_new_project():
    project_id = str(uuid.uuid4())
    new_project = {
        "id": project_id,
        "title": st.session_state.new_project_title,
        "type": st.session_state.new_project_type,
        "interface": st.session_state.new_project_interface,
        "model": st.session_state.new_project_model if "new_project_model" in st.session_state else "",
        "test_url": st.session_state.new_project_url if "new_project_type" == "自动测试" else st.session_state.manual_url,
        "api_key": st.session_state.new_project_api_key if "new_project_api_key" in st.session_state else "",
        "user": st.session_state.new_project_user if "new_project_user" in st.session_state else "",
        "custom_prompt": st.session_state.get("custom_prompt_text", ""),
        "created_at": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "results": []
    }
    logger.info(f"创建新项目 - 标题: {new_project['title']}, 类型: {new_project['type']}, ID: {project_id}")
    
    st.session_state.projects.append(new_project)
    st.session_state.current_project = project_id
    st.session_state.test_results[project_id] = []
    st.session_state.show_new_project = False
    
    # 重置所有相关的会话状态
    st.session_state.chat_history = []
    st.session_state.show_rating = False
    st.session_state.current_question = None
    st.session_state.current_answer = None
    st.session_state.show_evaluation_modal = False
    logger.debug("重置项目相关的会话状态")

# 切换项目
def switch_project(project_id):
    logger.info(f"切换到项目 ID: {project_id}")
    st.session_state.current_project = project_id
    # 获取当前项目信息
    current_project = next((p for p in st.session_state.projects if p["id"] == project_id), None)
    if current_project:
        logger.debug(f"加载项目配置 - 标题: {current_project['title']}, 类型: {current_project['type']}")
        # 根据项目类型设置相应的会话状态
        if current_project["type"] == "自动测试":
            st.session_state.new_project_model = current_project.get("model", "")
            st.session_state.new_project_url = current_project.get("test_url", "")
            st.session_state.new_project_api_key = current_project.get("api_key", "")
            st.session_state.new_project_user = current_project.get("user", "")
        else:  # 手动测试
            st.session_state.manual_url = current_project.get("test_url", "")
            st.session_state.manual_api_key = current_project.get("api_key", "")
            st.session_state.manual_user = current_project.get("user", "")
        
        # 设置自定义提示词状态
        st.session_state.custom_prompt_text = current_project.get("custom_prompt", "")
    
    # 重置其他会话状态
    st.session_state.chat_history = []
    st.session_state.show_rating = False
    st.session_state.current_question = None
    st.session_state.current_answer = None
    st.session_state.show_evaluation_modal = False
    logger.debug("重置项目相关的会话状态")

# 显示评估模态框
def show_evaluation_modal(question, answer):
    logger.debug(f"显示评估模态框 - 问题: {question[:50]}...")
    st.session_state.show_evaluation_modal = True
    st.session_state.current_question = question
    st.session_state.current_answer = answer

# 保存评估结果
def save_evaluation():
    project_id = st.session_state.current_project
    logger.info(f"保存评估结果到项目 ID: {project_id}")
    
    project_index = next((i for i, p in enumerate(st.session_state.projects) if p["id"] == project_id), None)
    
    if project_index is not None:
        result = {
            FIELD_QUESTION: st.session_state.current_question,
            FIELD_EXPECTED_ANSWER: st.session_state.expected_answer if "expected_answer" in st.session_state else "",
            FIELD_ACTUAL_ANSWER: st.session_state.current_answer,
            FIELD_FINAL_SCORE: st.session_state.evaluation_score,
            FIELD_TAGS: st.session_state.evaluation_tags.split(",") if st.session_state.evaluation_tags else [],
            "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        
        logger.debug(f"评估结果 - 分数: {result[FIELD_FINAL_SCORE]}, 标签: {result[FIELD_TAGS]}")
        
        # 转换为统一字段名称格式，用于judge_by_ai函数
        judge_data = {
            FIELD_QUESTION: result[FIELD_QUESTION],
            FIELD_EXPECTED_ANSWER: result[FIELD_EXPECTED_ANSWER],
            FIELD_ACTUAL_ANSWER: result[FIELD_ACTUAL_ANSWER],
            FIELD_TAGS: result[FIELD_TAGS]
        }
        
        st.session_state.test_results[project_id].append(result)
        st.session_state.projects[project_index]["results"].append(result)
        st.session_state.show_evaluation_modal = False
        logger.info("评估结果保存成功")

# 自定义提示词弹窗
@st.dialog("🔧 自定义评估提示词", width="large")
def show_custom_prompt_dialog():
    """显示自定义提示词弹窗"""
    current_project = next((p for p in st.session_state.projects if p["id"] == st.session_state.current_project), None)
    if not current_project:
        st.error("未找到当前项目")
        return
    
    # 添加CSS样式来调整文本区域宽度
    st.markdown("""
    <style>
    .stTextArea > div > div > textarea {
        width: 100% !important;
        min-height: 400px !important;
    }
    </style>
    """, unsafe_allow_html=True)
    
    # 获取当前项目的自定义提示词
    current_custom_prompt = current_project.get("custom_prompt", "")
    
    st.markdown("### 📖 默认提示词预览")
    with st.expander("点击查看默认提示词", expanded=False):
        st.code(JUDGEMENT_PROMPT, language="text")
    
    st.markdown("### ✏️ 自定义提示词")
    st.info("💡 自定义提示词将替代默认提示词用于AI评估。留空将使用默认提示词。")
    
    custom_prompt_input = st.text_area(
        "输入您的自定义评估提示词", 
        value=current_custom_prompt, 
        height=400, 
        key="dialog_custom_prompt_text",
        help="自定义提示词将用于AI评估答案的质量。可以根据您的评估标准来调整。",
        placeholder="请输入自定义的AI评估提示词...",
    )
    
    col1, col2 = st.columns(2)
    with col1:
        if st.button("💾 保存提示词", type="primary", use_container_width=True):
            # 更新当前项目的自定义提示词
            project_index = next((i for i, p in enumerate(st.session_state.projects) if p["id"] == current_project["id"]), None)
            if project_index is not None:
                st.session_state.projects[project_index]["custom_prompt"] = custom_prompt_input
                st.success("✅ 自定义提示词已保存")
                # 同步更新session_state中的值
                st.session_state.custom_prompt_text = custom_prompt_input
                time.sleep(1)  # 给用户时间看到成功消息
                st.rerun()
    
    with col2:
        if st.button("❌ 取消", use_container_width=True):
            st.rerun()

# 导出结果为JSON
def export_json(project_id):
    logger.info(f"开始导出JSON - 项目ID: {project_id}")
    project = next((p for p in st.session_state.projects if p["id"] == project_id), None)
    if project:
        export_data = {
            "title": project["title"],
            "type": project["type"],
            "model": project["model"],
            "test_url": project["test_url"],
            "results": project["results"]
        }
        
        # 将数据转换为JSON字符串
        json_str = json.dumps(export_data, ensure_ascii=False, indent=4)
        
        # 返回JSON字符串和文件名
        timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        filename = f"{project['title']}_{project['type']}_{timestamp}.json"
        logger.info(f"JSON导出成功 - 文件名: {filename}")
        
        return json_str, filename
    logger.warning(f"导出JSON失败 - 未找到项目ID: {project_id}")
    return None, None

# 导出结果为CSV/Excel
def export_csv(project_id, format="csv"):
    logger.info(f"开始导出{format.upper()} - 项目ID: {project_id}")
    project = next((p for p in st.session_state.projects if p["id"] == project_id), None)
    if project:
        results = project["results"]
        if results:
            df = pd.DataFrame(results)
            
            # 处理tags列表为字符串
            if "tags" in df.columns:
                df["tags"] = df["tags"].apply(lambda x: ",".join(x) if isinstance(x, list) else x)
            
            # 添加项目信息
            df["model"] = project["model"]
            df["test_url"] = project["test_url"]
            
            # 生成文件名
            timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
            filename = f"{project['title']}_{project['type']}_{timestamp}.{format}"
            
            try:
                # 将数据转换为相应格式的字节流
                if format == "csv":
                    csv_buffer = df.to_csv(index=True, encoding="utf-8-sig").encode()
                    logger.info(f"CSV导出成功 - 文件名: {filename}")
                    return csv_buffer, filename
                else:  # excel
                    excel_buffer = io.BytesIO()
                    df.to_excel(excel_buffer, index=True)
                    excel_buffer.seek(0)
                    logger.info(f"Excel导出成功 - 文件名: {filename}")
                    return excel_buffer, filename
            except Exception as e:
                logger.error(f"导出{format.upper()}时发生错误: {str(e)}, {traceback.format_exc()}")
                return None, None
    logger.warning(f"导出{format.upper()}失败 - 未找到项目ID: {project_id}")
    return None, None

# 处理自动测试
def run_auto_test(project_id):
    logger.info(f"开始自动测试 - 项目ID: {project_id}")
    st.session_state.test_running = True
    
    # 创建进度显示容器
    progress_container = st.container()
    
    try:
        uploaded_file = st.session_state.test_dataset
        if uploaded_file is not None:
            try:
                logger.info(f"读取测试数据集: {uploaded_file.name}")
                df = read_data_file(uploaded_file)
            except Exception as e:
                error_msg = f"读取文件时出错: {str(e)}"
                logger.error(error_msg)
                st.error(error_msg)
                return
            
            project_index = next((i for i, p in enumerate(st.session_state.projects) if p["id"] == project_id), None)
            if project_index is not None:
                project = st.session_state.projects[project_index]
                logger.info(f"开始处理项目: {project['title']}")
                
                # 清空之前的结果
                st.session_state.test_results[project_id] = []
                st.session_state.projects[project_index]["results"] = []
                
                # 实际API调用和评估
                total_cases = len(df)
                
                # 创建进度显示元素
                with progress_container:
                    st.markdown("### 🚀 测试进行中...")
                    progress_bar = st.progress(0)
                    status_text = st.empty()
                    current_question_display = st.empty()
                    current_step_display = st.empty()  # 用于显示当前步骤
                    
                    # 使用状态容器显示总体进度
                    with st.status(f"📊 正在处理 {total_cases} 个测试用例...", expanded=True) as status:
                        
                        for index, row in df.iterrows():
                            current_progress = (index + 1) / total_cases
                            progress_bar.progress(current_progress)
                            
                            logger.debug(f"处理测试用例 {index + 1}/{total_cases}")
                            question = row[FIELD_QUESTION]
                            url = project["test_url"]
                            dify_api_key = project["api_key"]
                            user = project["user"] if project["user"] else "default_user"
                            
                            # 更新状态显示
                            status_text.text(f"🔄 进度: {index + 1}/{total_cases} | 当前问题: {question[:50]}..." if len(question) > 50 else f"🔄 进度: {index + 1}/{total_cases} | 当前问题: {question}")
                            current_question_display.info(f"📝 **正在处理问题 {index + 1}:** {question}")
                            
                            # 检查必要参数
                            if not url:
                                error_msg = "测试接口URL不能为空"
                                logger.error(error_msg)
                                st.error(error_msg)
                                return
                            
                            if not dify_api_key:
                                error_msg = "API Key不能为空"
                                logger.error(error_msg)
                                st.error(error_msg)
                                return
                            
                            # 步骤1: 调用dify API获取回答
                            current_step_display.info(f"**步骤 {index + 1}.1:** 🔄 调用Dify API获取回答...")
                            logger.debug(f"调用Dify API - 问题: {question[:50]}...")
                            actual_answer = request_dify(
                                url=url,
                                api_key=dify_api_key,
                                user=user,
                                question=question
                            )
                            
                            # 准备评估数据
                            judge_data = {
                                FIELD_QUESTION: question,
                                FIELD_EXPECTED_ANSWER: row[FIELD_EXPECTED_ANSWER] if FIELD_EXPECTED_ANSWER in row else "",
                                FIELD_ACTUAL_ANSWER: actual_answer,
                                FIELD_ACCURACY: row[FIELD_ACCURACY] if FIELD_ACCURACY in row else -1,
                                FIELD_RELEVANCE: row[FIELD_RELEVANCE] if FIELD_RELEVANCE in row else -1,
                                FIELD_COHERENCE: row[FIELD_COHERENCE] if FIELD_COHERENCE in row else -1,
                                FIELD_TOXICITY: row[FIELD_TOXICITY] if FIELD_TOXICITY in row else -1,
                                FIELD_TAGS: row[FIELD_TAGS].split(",") if FIELD_TAGS in row and row[FIELD_TAGS] and isinstance(row[FIELD_TAGS], str) else []
                            }
                            
                            # 根据模型选择决定是否使用AI评估
                            if project["model"] == "None":
                                # 步骤2: 跳过AI评估
                                current_step_display.warning(f"**步骤 {index + 1}.2:** ⏭️ 跳过AI评估（选择了None模型）")
                                logger.debug("跳过AI评估，因为选择了None模型")
                                judge_result = {
                                    "score": -1,
                                    "comment": "未进行AI评估"
                                }
                            else:
                                # 步骤2: AI评估
                                current_step_display.info(f"**步骤 {index + 1}.2:** 🧠 使用 {project['model']} 进行AI评估...")
                                logger.debug(f"使用AI模型进行评估 - 模型: {project['model']}")
                                custom_prompt = project.get("custom_prompt", "")
                                judge_result = judge_by_ai(project["model"], judge_data, custom_prompt if custom_prompt else None)
                                
                                # 步骤3: 等待API限制
                                current_step_display.info(f"**步骤 {index + 1}.3:** ⏱️ 等待API限制...")
                                logger.debug("等待5秒以遵守请求限制...")
                                time.sleep(5)
                            
                            # 创建结果记录
                            result = {
                                FIELD_QUESTION: question,
                                FIELD_EXPECTED_ANSWER: judge_data[FIELD_EXPECTED_ANSWER],
                                FIELD_ACTUAL_ANSWER: actual_answer,
                                FIELD_ACCURACY: judge_data[FIELD_ACCURACY],
                                FIELD_RELEVANCE: judge_data[FIELD_RELEVANCE],
                                FIELD_COHERENCE: judge_data[FIELD_COHERENCE],
                                FIELD_TOXICITY: judge_data[FIELD_TOXICITY],
                                FIELD_TAGS: judge_data[FIELD_TAGS],
                                FIELD_FINAL_SCORE: judge_result.get("score", -1),
                                FIELD_COMMENT: judge_result.get("comment", ""),
                                "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                            }
                            
                            # 保存结果
                            st.session_state.test_results[project_id].append(result)
                            st.session_state.projects[project_index]["results"].append(result)
                            
                            # 显示当前问题完成状态
                            current_step_display.success(f"✅ **问题 {index + 1} 完成** - 得分: {result[FIELD_FINAL_SCORE]}")
                            logger.debug(f"测试用例 {index + 1}/{total_cases} 完成 - 得分: {result[FIELD_FINAL_SCORE]}")
                            
                            # 短暂停顿让用户看到完成状态
                            time.sleep(0.5)
                        
                        # 完成所有测试
                        progress_bar.progress(1.0)
                        status_text.success(f"🎉 测试完成！处理了 {total_cases} 个测试用例")
                        current_question_display.success(f"✅ 所有 {total_cases} 个测试用例已完成！")
                        current_step_display.success(f"🎊 **全部完成！** 成功处理了 {total_cases} 个测试用例")
                        status.update(label="✅ 测试完成！", state="complete")
                
                logger.info(f"自动测试完成 - 总用例数: {total_cases}")
    
    except Exception as e:
        error_msg = f"测试过程中出错: {str(e)}, {traceback.format_exc()}"
        logger.error(error_msg)
        st.error(error_msg)
    
    finally:
        st.session_state.test_running = False
        logger.info("测试会话结束")

# 侧边栏 - 项目列表
with st.sidebar:
    st.title("🤖 AI 测试工具")
    
    # 新建项目按钮
    if st.button("➕ 新建项目", type="primary"):
        st.session_state.show_new_project = True
    
    # 项目列表
    st.subheader("📁 项目列表")
    for project in st.session_state.projects:
        project_type_emoji = "🤖" if project['type'] == "自动测试" else "👤"
        if st.button(f"{project_type_emoji} {project['title']} ({project['type']})", key=f"project_{project['id']}"):
            switch_project(project['id'])

# 新建项目表单
if st.session_state.get("show_new_project", False):
    with st.form("new_project_form"):
        st.subheader("✨ 新建项目")
        st.text_input("📝 项目标题", key="new_project_title")
        st.selectbox("🔧 测试类型", ["自动测试", "手动测试"], key="new_project_type")
        st.selectbox("🔗 测试接口", ["Dify"], key="new_project_interface")
        
        submitted = st.form_submit_button("🚀 创建项目", type="primary")
        if submitted:
            create_new_project()

# 主界面
if st.session_state.current_project:
    current_project = next((p for p in st.session_state.projects if p["id"] == st.session_state.current_project), None)
    
    if current_project:
        st.title(current_project["title"])
        st.subheader(f"测试类型: {current_project['type']}")
        
        # 自动测试界面
        if current_project["type"] == "自动测试":
            with open(sample_file, "rb") as f:
                st.download_button(label="📥 下载测试数据模板", file_name="template.csv", data=f, type="secondary")
            
            with st.form("auto_test_form"):
                st.subheader(f"🤖 {current_project['interface']} 自动测试配置")
                
                # 自定义提示词按钮（移到上面）
                st.markdown("#### 🎯 评估配置")
                col_prompt, col_spacer = st.columns([2, 3])
                with col_prompt:
                    if st.form_submit_button("🔧 自定义评估提示词", type="secondary", help="点击自定义AI评估标准和提示词"):
                        st.session_state.show_custom_prompt_dialog = True
                        st.rerun()
                
                st.markdown("#### 📂 数据配置")
                uploaded_file = st.file_uploader("上传测试数据集 (CSV,Json,Excel格式)", type=["csv","json","xlsx"], key="test_dataset")
                
                st.markdown("#### ⚙️ 模型配置")
                col1, col2 = st.columns(2)
                with col1:
                    st.selectbox("🧠 AI模型", OPENAI_MODELS+DEEPSEEK_MODELS, key="new_project_model")
                
                with col2:
                    st.text_input("🔗 测试接口URL (必填)", key="new_project_url", help="Dify工作流的API端点")
                    #default='http://192.168.41.62/v1/chat-messages'
                
                if st.session_state.new_project_interface == "Dify":
                    st.markdown("#### 🔐 认证配置")
                    col3, col4 = st.columns(2)
                    with col3:
                        st.text_input("🔑 API Key (必填)", key="new_project_api_key", type="password", help="Dify应用的API密钥")
                        # default = "app-mqCCfa0WMgb2aq94hf5Y9XxF"
                    
                    with col4:
                        st.text_input("👤 用户标识", key="new_project_user", help="用于标识测试用户")
                
                # 开始测试按钮
                st.markdown("---")
                col_test, col_spacer2 = st.columns([2, 3])
                with col_test:
                    submitted = st.form_submit_button("🚀 开始自动测试", type="primary", help="配置完成后点击开始测试")
                if submitted:
                    # 更新当前项目的配置
                    project_index = next((i for i, p in enumerate(st.session_state.projects) if p["id"] == current_project["id"]), None)
                    if project_index is not None:
                        # 更新项目配置
                        st.session_state.projects[project_index]["model"] = st.session_state.new_project_model
                        st.session_state.projects[project_index]["test_url"] = st.session_state.new_project_url
                        st.session_state.projects[project_index]["api_key"] = st.session_state.new_project_api_key
                        st.session_state.projects[project_index]["user"] = st.session_state.new_project_user
                        # 保存自定义提示词
                        if "custom_prompt_text" in st.session_state:
                            st.session_state.projects[project_index]["custom_prompt"] = st.session_state.custom_prompt_text
                        
                        # 输出调试信息
                        st.write(f"测试接口URL: {st.session_state.new_project_url}")
                        st.write(f"API Key: {'*' * len(st.session_state.new_project_api_key)}")
                        st.write(f"用户标识: {st.session_state.new_project_user}")
                        
                        # 运行测试
                        run_auto_test(current_project["id"])
            
            # 显示测试结果
            if current_project["id"] in st.session_state.test_results and st.session_state.test_results[current_project["id"]]:
                st.subheader("📊 测试结果")
                
                results = st.session_state.test_results[current_project["id"]]
                df = pd.DataFrame(results)
                
                # 处理tags列表为字符串
                if FIELD_TAGS in df.columns:
                    df[FIELD_TAGS] = df[FIELD_TAGS].apply(lambda x: ",".join(x) if isinstance(x, list) else x)
                
                st.dataframe(df, use_container_width=True)
                
                # 添加分析报告按钮
                st.markdown("#### 📈 数据分析")
                if st.button("📊 查看分析报告", type="secondary"):
                    st.session_state.show_analysis_report = True
                
                # 显示分析报告
                if st.session_state.show_analysis_report:
                    st.subheader("📈 分析报告")
                    # 使用通用函数显示分析报告
                    st.session_state.selected_tags = show_analysis_report(results, st.session_state.selected_tags)
                    
                    # 添加关闭按钮
                    if st.button("❌ 关闭分析报告"):
                        st.session_state.show_analysis_report = False
                        st.session_state.selected_tags = []
                        st.rerun()
                
                # 下载按钮
                st.markdown("#### 💾 导出数据")
                col1, col2, col3 = st.columns(3)
                with col1:
                    json_data, json_filename = export_json(current_project["id"])
                    if json_data and json_filename:
                        st.download_button(
                            label="📄 下载为JSON",
                            data=json_data,
                            file_name=json_filename,
                            mime="application/json",
                            type="secondary"
                        )
                
                with col2:
                    csv_data, csv_filename = export_csv(current_project["id"], "csv")
                    if csv_data is not None and csv_filename:
                        st.download_button(
                            label="📋 下载为CSV",
                            data=csv_data,
                            file_name=csv_filename,
                            mime="text/csv",
                            type="secondary"
                        )
                
                with col3:
                    excel_data, excel_filename = export_csv(current_project["id"], "xlsx")
                    if excel_data is not None and excel_filename:
                        st.download_button(
                            label="📊 下载为Excel",
                            data=excel_data,
                            file_name=excel_filename,
                            mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                            type="secondary"
                        )
        
        # 手动测试界面
        else:  # 手动测试
            st.subheader("👤 手动测试")
            
            # 配置区域
            with st.expander(f"⚙️ {current_project['interface']} 手动测试配置", expanded=True):
                col1, col2 = st.columns(2)
                with col1:
                    st.text_input("🔗 测试接口URL (必填)", key="manual_url")
                
                with col2:
                    st.text_input("🔑 API Key (必填)", key="manual_api_key", type="password")
                
                if st.session_state.new_project_interface == "Dify":
                    col3, col4 = st.columns(2)
                    with col3:
                        st.text_input("👤 用户标识", key="manual_user")
                
                # 添加保存配置按钮
                if st.button("💾 保存配置", type="secondary"):
                    project_index = next((i for i, p in enumerate(st.session_state.projects) if p["id"] == st.session_state.current_project), None)
                    if project_index is not None:
                        # 更新项目配置
                        st.session_state.projects[project_index]["test_url"] = st.session_state.manual_url
                        st.session_state.projects[project_index]["api_key"] = st.session_state.manual_api_key
                        st.session_state.projects[project_index]["user"] = st.session_state.manual_user
                        st.success("✅ 配置已保存")
            
            # 聊天历史显示区域
            st.markdown("#### 💬 对话历史")
            chat_container = st.container()
            with chat_container:
                for i, message in enumerate(st.session_state.chat_history):
                    if message["type"] == "question":
                        st.write(f"**🙋 Q{i//2+1} 您:** {message['content']}")
                    else:
                        st.write(f"**🤖 AI:** {message['content']}")
                        if "score" in message:
                            st.write(f"**⭐ 评分:** {message['score']}/10")
                        if "tags" in message and message["tags"]:
                            st.write(f"**🏷️ 标签:** {', '.join(message['tags'])}")
                        if "comment" in message and message["comment"]:
                            st.write(f"**💭 评论:** {message['comment']}")
                        st.write("---")
            
            # 输入区域
            st.markdown("#### ❓ 提问区域")
            with st.form("chat_form"):
                col1, col2 = st.columns([4, 1])
                with col1:
                    question = st.text_input("💭 输入问题", key="manual_question", placeholder="请输入您要测试的问题...")
                with col2:
                    st.write("")  # 占位
                    submit = st.form_submit_button("📤 发送", type="primary")
            
                if submit and question:
                    # 确保URL和user参数不为空
                    url = st.session_state.manual_url
                    api_key = st.session_state.manual_api_key
                    user = st.session_state.manual_user if st.session_state.manual_user else "default_user"
                    
                    if not url:
                        st.error("测试接口URL不能为空")
                    elif not api_key:
                        st.error("API Key不能为空")
                    else:
                        # 更新项目的配置信息
                        project_index = next((i for i, p in enumerate(st.session_state.projects) if p["id"] == st.session_state.current_project), None)
                        if project_index is not None:
                            st.session_state.projects[project_index]["test_url"] = url
                            st.session_state.projects[project_index]["api_key"] = api_key
                            st.session_state.projects[project_index]["user"] = user
                        
                        # 添加用户问题到历史记录
                        st.session_state.chat_history.append({
                            "type": "question",
                            "content": question,
                            "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        })
                        
                        # 调用API获取回答
                        ai_response = request_dify(
                            url=url,
                            api_key=api_key,
                            user=user,
                            question=question
                        )
                        
                        # 添加AI回答到历史记录
                        st.session_state.chat_history.append({
                            "type": "answer",
                            "content": ai_response,
                            "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        })
                        
                        # 设置状态以显示评分界面
                        st.session_state.show_rating = True
                        
                        # 重新渲染聊天历史
                        st.rerun()
                        st.session_state.current_question = question
                        st.session_state.current_answer = ai_response
                        
                        # 重置表单状态
                        if "manual_question" in st.session_state:
                            del st.session_state.manual_question
            
            # 评分界面（在chat_form外部）
            if st.session_state.get("show_rating", False):
                st.markdown("#### ⭐ 评分区域")
                with st.form("rating_form"):
                    st.info("📝 请为刚才的AI回答进行评分")
                    score = st.radio(
                        "⭐ 评分 (1-10分)",
                        options=list(range(1, 11)),
                        horizontal=True,
                        key="evaluation_score"
                    )
                    tags = st.text_input("🏷️ 标签 (用逗号分隔)", key="evaluation_tags",
                                       help="输入相关标签，多个标签用逗号分隔",
                                       placeholder="例如：准确,相关,有用")
                    comment = st.text_area("💭 评论 (可选)", key="evaluation_comment",
                                         help="输入对回答的评论或说明",
                                         placeholder="请输入您对这个回答的评价...")
                    
                    if st.form_submit_button("💾 保存评分", type="primary"):
                        # 从聊天历史中获取最后一条问题和回答
                        if len(st.session_state.chat_history) >= 2:
                            last_question = st.session_state.chat_history[-2]["content"]
                            last_answer = st.session_state.chat_history[-1]["content"]
                            
                            # 处理标签，确保是列表格式
                            tags_list = split_tags(tags) if tags else []
                            
                            # 更新最后一条AI回答的评分和标签
                            st.session_state.chat_history[-1]["score"] = score
                            st.session_state.chat_history[-1]["tags"] = tags_list
                            st.session_state.chat_history[-1]["comment"] = comment
                            
                            # 保存到测试结果
                            project_id = st.session_state.current_project
                            project_index = next((i for i, p in enumerate(st.session_state.projects) if p["id"] == project_id), None)
                            
                            if project_index is not None:
                                result = {
                                    FIELD_QUESTION: last_question,
                                    FIELD_EXPECTED_ANSWER: "",
                                    FIELD_ACTUAL_ANSWER: last_answer,
                                    FIELD_FINAL_SCORE: score,
                                    FIELD_TAGS: tags_list,
                                    FIELD_COMMENT: comment,
                                    "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                    "test_url": st.session_state.manual_url
                                }
                                
                                st.session_state.test_results[project_id].append(result)
                                st.session_state.projects[project_index]["results"].append(result)
                            
                            # 重置评分状态
                            st.session_state.show_rating = False
                            
                            # 重新渲染页面
                            st.rerun()

            # 显示测试结果
            if current_project["id"] in st.session_state.test_results and st.session_state.test_results[current_project["id"]]:
                st.subheader("📊 测试结果")
                
                results = st.session_state.test_results[current_project["id"]]
                df = pd.DataFrame(results)
                
                # 处理tags列表为字符串
                if FIELD_TAGS in df.columns:
                    df[FIELD_TAGS] = df[FIELD_TAGS].apply(lambda x: ",".join(x) if isinstance(x, list) else x)
                
                st.dataframe(df, use_container_width=True)
                
                # 添加分析报告按钮
                st.markdown("#### 📈 数据分析")
                if st.button("📊 查看分析报告", type="secondary"):
                    st.session_state.show_analysis_report = True
                
                # 显示分析报告
                if st.session_state.show_analysis_report:
                    st.subheader("📈 分析报告")
                    # 使用通用函数显示分析报告
                    st.session_state.selected_tags = show_analysis_report(results, st.session_state.selected_tags)
                    
                    # 添加关闭按钮
                    if st.button("❌ 关闭分析报告"):
                        st.session_state.show_analysis_report = False
                        st.session_state.selected_tags = []
                        st.rerun()
                
                # 下载按钮
                st.markdown("#### 💾 导出数据")
                col1, col2, col3 = st.columns(3)
                with col1:
                    json_data, json_filename = export_json(current_project["id"])
                    if json_data and json_filename:
                        st.download_button(
                            label="📄 下载为JSON",
                            data=json_data,
                            file_name=json_filename,
                            mime="application/json",
                            type="secondary"
                        )
                
                with col2:
                    csv_data, csv_filename = export_csv(current_project["id"], "csv")
                    if csv_data is not None and csv_filename:
                        st.download_button(
                            label="📋 下载为CSV",
                            data=csv_data,
                            file_name=csv_filename,
                            mime="text/csv",
                            type="secondary"
                        )
                
                with col3:
                    excel_data, excel_filename = export_csv(current_project["id"], "xlsx")
                    if excel_data is not None and excel_filename:
                        st.download_button(
                            label="📊 下载为Excel",
                            data=excel_data,
                            file_name=excel_filename,
                            mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                            type="secondary"
                        )

# 评估模态框
if st.session_state.show_evaluation_modal:
    with st.form("evaluation_form"):
        st.subheader("评估AI回答")
        
        col1, col2 = st.columns([1, 2])
        with col1:
            st.write("**问题:**")
            st.write(st.session_state.current_question)
            
            if "expected_answer" in st.session_state and st.session_state.expected_answer:
                st.write("**期望答案:**")
                st.write(st.session_state.expected_answer)
        
        with col2:
            st.write("**AI回答:**")
            st.write(st.session_state.current_answer)
            
            st.write("**评分:**")
            st.radio(
                "评分 (1-10分)",
                options=list(range(1, 11)),
                horizontal=True,
                key="evaluation_score"
            )
            
            st.text_input("标签 (用逗号分隔)", key="evaluation_tags",
                         help="输入相关标签，多个标签用逗号分隔")
        
        col3, col4, col5 = st.columns(3)
        with col3:
            if st.form_submit_button("保存评估"):
                save_evaluation()
        with col4:
            if st.form_submit_button("继续提问"):
                st.session_state.show_evaluation_modal = False
                # 使用 Streamlit 的 rerun 功能来重置输入框
                st.rerun()
        with col5:
            if st.form_submit_button("取消"):
                st.session_state.show_evaluation_modal = False

else:
    # 欢迎界面
    if not st.session_state.current_project:
        st.title("🎉 欢迎使用AI测试工具")
        st.write("🚀 这是一个基于Streamlit开发的AI问答测试工具。该工具提供了自动化测试和手动测试两种方式来评估AI模型的性能。")
        
        st.subheader("✨ 功能特点")
        st.markdown("""
        - 🎨 直观的用户界面
        - 📁 侧边栏项目记录
        - 🤖 支持自动化测试
        - 👤 支持手动测试
        - 📊 测试结果实时展示
        - 💾 支持导出测试结果为JSON、CSV、Excel格式
        - 🔧 支持自定义AI评估提示词
        - ⚡ 支持跳过AI评估（None模型选项）

        # !!!‼️ ATTENTION ‼️!!!! 重要的事情说三遍！！！！
        - ‼️请记得保存结果，否则一旦刷新页面，结果也会丢失！！！！‼️
        - 请记得保存结果，否则一旦刷新页面，结果也会丢失！！！！
        - 请记得保存结果，否则一旦刷新页面，结果也会丢失！！！！
        - ‼️手动测试时，请记得保存评分！！！Streamlit只能做到这样了！！！‼️
        - 手动测试时，请记得保存评分！！！Streamlit只能做到这样了！！！
        - 手动测试时，请记得保存评分！！！Streamlit只能做到这样了！！！

        📖 **使用说明文档:** [README.md](http://git.poweroak.ltd/ShiYuXin/simple-ai-tester/-/blob/main/README.md)
        """)
        
        st.subheader("🚀 开始使用")
        st.info("💡 点击左侧边栏的 ➕ 新建项目按钮开始使用！")

# 处理自定义提示词弹窗
if st.session_state.get("show_custom_prompt_dialog", False):
    show_custom_prompt_dialog()
    st.session_state.show_custom_prompt_dialog = False